<template>
  <h1 style="font-size: 1.25rem; margin-bottom: 1.25rem">
    {{ $t("币币兑换") }}/{{ $t("订单记录") }}
  </h1>

  <el-card>
    <div class="flex">
      <el-input
        v-model="filterForm.order_no"
        style="max-width: 30%; padding: 0.5rem"
        :placeholder="$t('订单号搜索')"
        @change="filterList()"
      ></el-input>
      <el-select
        v-model="filterForm.status"
        style="max-width: 20%; padding: 0.5rem"
        :placeholder="$t('订单状态')"
        @change="filterList()"
      >
        <el-option
          v-for="item in orderStatus"
          :key="item.key"
          :label="item.name"
          :value="item.value"
        ></el-option>
      </el-select>

      <el-select
        v-model="filterForm.from_coin_name"
        style="max-width: 20%; padding: 0.5rem"
        :placeholder="$t('买入货币')"
        @change="filterList()"
      >
        <el-option
          v-for="item in coinList"
          :key="item.coin_name"
          :label="item.coin_name"
          :value="item.coin_name"
        ></el-option>
      </el-select>
      <el-select
        v-model="filterForm.to_coin_name"
        style="max-width: 20%; padding: 0.5rem"
        :placeholder="$t('卖出货币')"
        @change="filterList()"
      >
        <el-option
          v-for="item in coinList"
          :key="item.coin_name"
          :label="item.coin_name"
          :value="item.coin_name"
        ></el-option>
      </el-select>
    </div>

    <el-table :data="orderList" v-loading="loading">
      <el-table-column prop="order_no" :label="$t('订单号')" width="250" />
      <el-table-column align="center" :label="$t('订单状态')" width="180">
        <template #default="scope">
          <el-tag :type="getOrderStatusName(scope.row.status).type">
            {{ getOrderStatusName(scope.row.status).name }}
          </el-tag>
          <br />
          <el-text :type="getOrderStatusName(scope.row.status).type">
            {{ scope.row.countDownName }}
          </el-text>
        </template>
      </el-table-column>
      <el-table-column align="center" :label="$t('从')" width="180">
        <template #default="scope">
          {{ scope.row.from_quantity }} {{ scope.row.from_coin_name }}
        </template>
      </el-table-column>
      <el-table-column align="center" :label="$t('至')" width="180">
        <template #default="scope">
          {{ scope.row.to_quantity }} {{ scope.row.to_coin_name }}
        </template>
      </el-table-column>
      <el-table-column align="center" :label="$t('汇率')" width="250">
        <template #default="scope">
          1 {{ scope.row.from_coin_name }} = {{ scope.row.price }}
          {{ scope.row.to_coin_name }}
        </template>
      </el-table-column>
      <el-table-column align="center" :label="$t('提交时间')" width="180">
        <template #default="scope">
          {{
            dayjs(scope.row.create_time * 1000).format("YYYY-MM-DD HH:mm:ss")
          }}
        </template>
      </el-table-column>

      <el-table-column
        fixed="right"
        align="center"
        :label="$t('操作')"
        width="150"
      >
        <template #default="scope">
          <el-button
            round
            icon="MoreFilled"
            class="cursor-pointer"
            @click="showCurrentDetail(scope)"
            >{{ $t("查看") }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="flex justify-center mt-5">
      <el-pagination background
        layout="total, sizes, prev, pager, next, jumper"
        :total="pageable.total"
        :default-page-size="pageable.pageSize"
        :default-current-page="pageable.pageNum"
        :page-sizes="[10, 25, 50, 100]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange" />
    </div>
  </el-card>

  <swapOrderDetailDrawer
    :show="isShoOrderDetail"
    :orderNo="currentOrderNo"
    @close="
      (val) => {
        if (val === 'refresh') {
          refresh();
        }
        currentOrderNo = '';
      }
    "
  />
</template>
<script setup>
import swapOrderDetailDrawer from "./components/swapOrderDetailDrawer.vue";
import { ref, reactive, computed, watch, onBeforeUnmount } from "vue";
import { getSwapOrderPagesApi, getSwapSymbolsApi } from "@/api/swap/index";
import dayjs from "dayjs";
import duration from "dayjs/plugin/duration";
import { useStatusStore } from "@/store/modules/status";
dayjs.extend(duration);
const statusStore = useStatusStore();
const loading = ref(false);
const coinList = ref([]);
// 获取币种列表
const getSwapSymbolsInfo = async (name) => {
  try {
    const symbolsRes = await getSwapSymbolsApi();
    if (symbolsRes?.length) {
      coinList.value = symbolsRes;
    }
    getSwapOrderList();
  } catch (e) {
    return false;
  }
};

const orderStatus = ref([
  { key: 1, name: "已完成", value: "complete", type: "success" },
  { key: 2, name: "进行中", value: "pending", type: "warning" },
  { key: 3, name: "已取消", value: "cancel", type: "danger" },
]);

const orderList = ref([]);
const totalCount = ref(0);
// 分页
const pageable = reactive({
  pageNum: 1,
  pageSize: 10,
  total: 0,
});
const getSwapOrderList = async (addQuery) => {
  try {
    loading.value = true;
    const { page, list } = await getSwapOrderPagesApi({
      ...pageable,
      ...addQuery,
    });
    if (list?.length) {
      orderList.value = list;
      totalCount.value = page.total_count;
    }
    loading.value = false;
  } catch (e) {
    loading.value = false;
    return false;
  }
};

const countDownList = computed(() => {
  return orderList.value.filter((i) => [0, 2].includes(i.status));
});
watch(countDownList, (newVal) => {
  newVal.forEach((item) => {
    countDown(item);
  });
});
const getOrderStatusName = (status) => {
  return statusStore.swapOrderStatus.find((i) => status === i.key);
};

const countDown = (item) => {
  if (item.countDown) {
    clearInterval(item.countDown);
  }
  let diffTime = (item.expire_time - item.ts) * 1000;
  if (diffTime > 0) {
    item.countDown = setInterval(() => {
      diffTime = diffTime - 1000;
      item.countDownName = dayjs(diffTime).format("hh:mm:ss");
    }, 1000);
  } else {
    clearInterval(item.countDown);
    item.status = 3;
  }
};
const currentOrderNo = ref("");
const isShoOrderDetail = ref(false);
const showCurrentDetail = (scope) => {
  currentOrderNo.value = scope.row.order_no;
};
watch(currentOrderNo, (newVal) => {
  isShoOrderDetail.value = newVal ? true : false;
});
const handleCurrentChange = async (number) => {
  pageable.pageNum = number;
  await getSwapOrderList();
};
// 条数
const handleSizeChange = number => {
  pageable.pageSize = number;
  getTbaleData();
};
//筛选组件
const filterForm = reactive({
  order_no: "",
  status: "",
});
const filterList = async (e) => {
  const newQuery = Object.entries(filterForm).reduce((acc, [key, value]) => {
    if (value) {
      acc[key] = value;
    }
    return acc;
  }, {});
  pageable.page = 1;
  await getSwapOrderList(newQuery);
};

onBeforeUnmount(() => {
  countDownList.value.forEach((item) => {
    clearInterval(item.countDown);
  });
});

const refresh = async () => {
  pageable.page = 1;
  await getSwapOrderList();
};
getSwapSymbolsInfo();
</script>
<style lang="scss"></style>
